package com.springsource.a03beanlifecycle;

import org.slf4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {
    private static final Logger log = org.slf4j.LoggerFactory.getLogger(MyBeanPostProcessor.class);


    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (beanName.equals("lifecycleBean"))
            log.info("实例化之前执行，如果不返回null，则会替换掉原有的bean: {}", beanName);
        // 如果不返回null，则会替换掉原有的bean
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (beanName.equals("lifecycleBean"))
            log.info("实例化之后执行，如果返回false，则跳过依赖注入阶段: {}", beanName);
        // 如果返回false则会跳过依赖注入的阶段
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        if (beanName.equals("lifecycleBean"))
            log.info("依赖注入阶段执行，如 @Autowired @Value @Resource: {}", pvs);
        return pvs;
    }
    // 以上三个方法来自于 InstantiationAwareBeanPostProcessor

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("lifecycleBean"))
            log.info("初始化之前执行，如解析@PostConstruct、@ConfigurationProperties，这里返回的对象会替换掉原本的bean: {}", beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("lifecycleBean"))
            log.info("初始化之后执行，如代理增强，这里返回的对象会替换掉原本的bean: {}", beanName);
        return bean;
    }

    @Override
    public void postProcessBeforeDestruction(Object o, String beanName) throws BeansException {
        if (beanName.equals("lifecycleBean"))
            log.info("销毁之前执行，如解析@PreDestory: {}", beanName);
    }
}
